<?php

declare(strict_types=1);

namespace App\Resource\Controller;

use App\Common\Constants\ErrorCode;
use App\Common\Controller\AbstractController;
use App\Common\Middleware\JwtAuthMiddleware;
use App\Common\Middleware\PermissionMiddleware;
use App\Resource\Model\CrdNavigationModel;
use App\Resource\Model\NavigationModel;
use App\Resource\Request\NavigationRequest;
use App\Resource\Service\NavigationService;
use App\Resource\Service\ResourceService;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\DeleteMapping;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\PostMapping;
use Hyperf\HttpServer\Annotation\PutMapping;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\HttpServer\Contract\RequestInterface;

/**
 * @Controller()
 */
class NavigationController extends AbstractController
{
    /**
     * @Inject()
     * @var NavigationService
     */
    private $navigationService;

    /**
     * @Inject()
     * @var ResourceService
     */
    private $resourceService;

    const NAVIGATION = 1;

    /**
     * 获取图文导航列表
     * @RequestMapping(path="/v1/navigation", methods="get")
     * @Middlewares({
     *     @Middleware(JwtAuthMiddleware::class),
     *     @Middleware(PermissionMiddleware::class)
     * })
     * @param RequestInterface $request
     *
     * @return array
     */
    public function index(RequestInterface $request)
    {
        $params = $request->all();
        $perPage = !empty($params['perpage']) ? $params['perpage'] : 15;
        $field = ['id', 'title', 'img', 'created_at', 'jump_type', 'sort', 'jump_url'];
        $res = $this->navigationService->getList($params, (int)$perPage, self::NAVIGATION, $field);

        if ($res['code']) {
            return $this->failed($res['code']);
        } else {
            return $this->success($res['data']->items(), '获取成功', $res['data']->total());
        }
    }

    /**
     * 获取图文导航信息
     * @RequestMapping(path="/v1/navigation/{id:\d+}", methods="get")
     * @Middlewares({
     *     @Middleware(JwtAuthMiddleware::class),
     *     @Middleware(PermissionMiddleware::class)
     * })
     * @param int $id
     *
     * @return array
     */
    public function info(int $id, RequestInterface $request)
    {
        $shopType = $request->input('shop_type') ?? null;
        $field = ['id', 'title', 'sort', 'img', 'jump_type', 'jump_url'];
        $res = $this->navigationService->getInfoById($id, self::NAVIGATION, $field, $shopType);
        if (!$res['code']) {
            return $this->success($res['data'], '获取成功');
        } else {
            return $this->failed($res['code']);
        }
    }

    /**
     * 添加图文导航
     * @PostMapping(path="/v1/navigation", methods="post")
     * @Middlewares({
     *     @Middleware(JwtAuthMiddleware::class),
     *     @Middleware(PermissionMiddleware::class)
     * })
     * @param NavigationRequest $request
     *
     * @return array
     */
    public function store(NavigationRequest $request)
    {
        $params = $request->validated();
        $res = $this->navigationService->add($params, self::NAVIGATION);
        if (!$res['code']) {
            return $this->success($res['data'], '操作成功');
        } else {
            return $this->failed($res['code']);
        }
    }

    /**
     * 编辑图文导航
     * @PutMapping(path="/v1/navigation/{id:\d+}", methods="put")
     * @Middlewares({
     *     @Middleware(JwtAuthMiddleware::class),
     *     @Middleware(PermissionMiddleware::class)
     * })
     * @param int $id
     * @param NavigationRequest $request
     *
     * @return array
     */
    public function update(int $id, NavigationRequest $request)
    {
        $params = $request->validated();
        $params['id'] = $id;
        $res = $this->navigationService->update($params, self::NAVIGATION);
        if (!$res['code']) {
            return $this->success($res['data'], '操作成功');
        } else {
            return $this->failed($res['code']);
        }
    }

    /**
     * 禁用/启用
     * @PutMapping(path="/v1/navigation/{id:\d+}/status", methods="put")
     * @Middlewares({
     *     @Middleware(JwtAuthMiddleware::class),
     *     @Middleware(PermissionMiddleware::class)
     * })
     * @param int $id
     *
     * @return array
     */
    public function editStatus(int $id, RequestInterface $request)
    {
        $shopType = $request->input('shop_type') ?? null;
        if (!$id) return $this->failed(ErrorCode::SYSTEM_INVALID);
        $res = $this->navigationService->editStatus('navigation', (int)$id, (string)self::NAVIGATION, $shopType);
        if (!$res['code']) {
            return $this->success($res['data'], '操作成功');
        } else {
            return $this->failed($res['code']);
        }
    }

    /**
     * 删除图文导航
     * @param RequestInterface $request
     * @DeleteMapping(path="/v1/navigation/{id:\d+}", methods="delete")
     * @Middlewares({
     *     @Middleware(JwtAuthMiddleware::class),
     *     @Middleware(PermissionMiddleware::class)
     * })
     * @param int $id
     *
     * @return array
     */
    public function delete(int $id, RequestInterface $request)
    {
        $shopType = $request -> input('shop_type') ?? null;
        $res = $this->navigationService->delete($id, self::NAVIGATION, $shopType);
        if (!$res['code']) {
            return $this->success($res['data'], '操作成功');
        } else {
            return $this->failed($res['code']);
        }
    }

    /**
     * 图文导航添加商品
     * @PostMapping(path="/v1/navigation/bind/goods", methods="post")
     * @Middlewares({
     *     @Middleware(JwtAuthMiddleware::class),
     *     @Middleware(PermissionMiddleware::class)
     * })
     * @param RequestInterface $request
     *
     * @return array
     */
    public function bindGoods(RequestInterface $request)
    {
        $navigationId = $request->input('navigation_id');
        $goodsId = $request->input('goods_id');
        $shopType = $request->input('shop_type') ?? null;
        if (!$navigationId || !$goodsId) return $this->failed(ErrorCode::PARAMS_INVALID);
        $res = $this->resourceService->bindGoods('navigation', (int)$navigationId, $goodsId, $shopType);
        if (!$res['code']) {
            return $this->success($res['data'], '操作成功');
        } else {
            return $this->failed($res['code']);
        }
    }

    /**
     * 轮播/弹窗 添加门店
     * @PostMapping(path="/v1/navigation/bind/shop", methods="post")
     * @Middlewares({
     *     @Middleware(JwtAuthMiddleware::class),
     *     @Middleware(PermissionMiddleware::class)
     * })
     * @param RequestInterface $request
     *
     * @return array
     */
    public function bindShop(RequestInterface $request)
    {
        $navigationId = $request->input('navigation_id');
        $shopId = $request->input('shop_id');
        $shopType = $request->input('shop_type') ?? null;
        if (!$navigationId || !$shopId) return $this->failed(ErrorCode::PARAMS_INVALID);
        $res = $this->resourceService->bindShop('navigation', (int)$navigationId, $shopId, self::NAVIGATION, $shopType);
        if (!$res['code']) {
            return $this->success($res['data'], '操作成功');
        } else {
            return $this->failed($res['code']);
        }
    }

    /**
     * 跳转组件列表
     * @Middlewares({
     *     @Middleware(JwtAuthMiddleware::class),
     *     @Middleware(PermissionMiddleware::class)
     * })
     * @RequestMapping(path="/v1/navigation/jump", methods="get")
     *
     * @return array
     */
    public function getJumpList()
    {
        $res = $this->navigationService->getJumpList();
        if (!$res['code']) {
            return $this->success($res['data'], '操作成功');
        } else {
            return $this->failed($res['code']);
        }
    }

    /**
     * 次日达商城 banner 接口
     *
     * @RequestMapping(path="/v1/api/navigation/next_day/banners", methods="get")
     *
     * @param RequestInterface $request
     * @return array
     */
    public function nextDayBanners(RequestInterface $request)
    {
        $shop_id = $request->input('shop_id',20200606322061);
        if (!$shop_id) {
            $shop_id=20200606322061;
        }
        $func = function ($m) use ($shop_id) {
            $nav_ids = $this->navigationService->getShopNavigationIds($shop_id, true);
            $field = ['id', 'title', 'img', 'jump_type', 'jump_url', 'sort', 'end_time'];
            return $m->select($field)
                ->whereIn('id', $nav_ids)
                ->where('start_time', '<', date('Y-m-d H:i:s'))
                ->where('end_time', '>', date('Y-m-d H:i:s'))
                ->where('type', CrdNavigationModel::TYPE_PLAY_IMAGE)
                ->orderBy('sort', 'desc')
                ->limit(10);
        };
        $res = $this->navigationService->hashGet($func, (string)$shop_id, 'crd:nav:' . CrdNavigationModel::TYPE_PLAY_IMAGE, 1);
        return $this->success($res, '获取成功');
    }

    /**
     * 次日达商城 图文导航 接口
     *
     * @RequestMapping(path="/v1/api/navigation/next_day/text_navigation", methods="get")
     *
     * @param RequestInterface $request
     * @return array
     */
    public function nextDayTextNavigation(RequestInterface $request)
    {
        $shop_id = $request->input('shop_id',20200606322061);
        if (!$shop_id) {
            $shop_id=20200606322061;
        }
        $func = function ($m) {
            $field = ['id', 'title', 'img', 'jump_type', 'jump_url', 'sort'];
            return $m->select($field)->where('type', CrdNavigationModel::TYPE_NAV)->orderBy('sort', 'desc')->limit(10);
        };
        $res = $this->navigationService->hashGet($func, 'list', 'crd:nav:' . CrdNavigationModel::TYPE_NAV, 1);
        return $this->success($res, '获取成功');
    }
}
